import type { VxeGridProps } from '@vben/plugins/src/vxe-table/types';

import type { TemplateTableConfig } from '#/views/onlineDesign/designPage/template/type/type';

import { tableConfig } from '#/views/onlineDesign/designPage/template/tableTemplate/config';

/**
 * 生成Table项
 * @param fields
 */
export const generateColumns = async (
  fields: Array,
): VxeGridProps['columns'] => {
  // 先过滤掉 fieldName 为 'del_flag' 的字段
  const filteredFields = fields.filter(
    (field) => field.fieldName !== 'del_flag',
  );

  /**
   * 辅助函数创建列
   * @param field 字段信息
   * @param showType 表格项默认值
   * @param index 排序
   * @param otherConfig 其他配置
   */
  const createColumnConfig = (
    field: Array,
    showType: string = 'text',
    index: number = 0,
    otherConfig: TemplateTableConfig.TableOtherColumnsConfig | undefined,
  ): TemplateTableConfig.TableColumnsConfig => {
    const baseConfig: TemplateTableConfig.TableColumnsConfig = {
      title: field.fieldAnnotation,
      field: toCamelCase(field.fieldName),
      align: 'center',
      type: undefined,
      width: undefined,
      visible: field.fieldName === 'create_time' ? true : field.isHandle,
      fixed: undefined,
      slots: undefined,
      showType,
      sequence: field.isHandle ? index + 3 : 98,
      otherConfig,
    };
    return baseConfig;
  };

  // 映射字段到列配置
  const mappingFieldsToColums = filteredFields.map((field, index) => {
    let showType = 'text';
    let otherConfig;
    if (field.fieldRelevance === 1) {
      showType = field.fieldRelevanceMode === 1 ? 'dict' : 'dictTable';
      if (field.fieldRelevanceMode === 1) {
        tableConfig.tableConfig.baseConfig.dict.exist = true;
        if (
          !tableConfig.tableConfig.baseConfig.dict.dictCodes.includes(
            field.fieldRelevanceModeValKey,
          )
        ) {
          tableConfig.tableConfig.baseConfig.dict.dictCodes.push(
            field.fieldRelevanceModeValKey,
          );
        }
        // 其他配置
        otherConfig = {
          dictCode: field.fieldRelevanceModeValKey,
        } as TemplateTableConfig.TableOtherColumnsConfig;
      }
    }
    return createColumnConfig(field, showType, index, otherConfig);
  });

  // 添加序号列
  if (tableConfig.tableConfig.baseConfig.showSerialNumber) {
    mappingFieldsToColums.unshift({
      title: '序号',
      field: undefined,
      align: 'center',
      type: 'seq',
      width: 50,
      fixed: 'left',
      visible: true,
      slots: undefined,
      showType: 'text',
      sequence: 2,
    });
  }

  // 添加选择列
  if (tableConfig.tableConfig.baseConfig.showChoose) {
    mappingFieldsToColums.unshift({
      title: '选择列',
      align: 'center',
      type: 'checkbox',
      width: 100,
      fixed: 'left',
      visible: true,
      slots: undefined,
      showType: 'text',
      sequence: 1,
    });
  }

  // 添加操作列
  mappingFieldsToColums.push({
    title: '操作',
    field: 'action',
    align: 'center',
    type: undefined,
    width: 120,
    fixed: 'right',
    visible: true,
    slots: { default: 'action' },
    showType: 'text',
    sequence: 99,
  });
  return mappingFieldsToColums;
};

// 排序
export function sort(colunms: Array) {
  // 对数组进行排序，基于 sequence 属性升序排序
  colunms.sort((a, b) => a.sequence - b.sequence);
}

/**
 * 重新加载列表
 *  调用接口的前提是必须调用：config.updateTableConfig() 方法进行赋值
 */
export const generateLoadColumns = async (): VxeGridProps['columns'] => {
  return tableConfig.tableConfig.columns;
};

/**
 * 将下划线分隔的字符串转换为驼峰命名
 * @param str 下划线分隔的字符串
 * @returns 驼峰命名的字符串
 */
function toCamelCase(str: string): string {
  return str.replaceAll(/([-_][a-z])/gi, ($1) => {
    return $1.toUpperCase().replace('-', '').replace('_', '');
  });
}
